package com.jumi.microservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumi.microservice.common.base.dto.BasePageResponse;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.core.aspect.WebLog;
import com.jumi.microservice.common.utils.ResultGenerator;
import com.jumi.microservice.constant.ExceptionEnum;
import com.jumi.microservice.domain.Department;
import com.jumi.microservice.domain.dto.DepartmentDTO;
import com.jumi.microservice.domain.vo.DepartmentVO;
import com.jumi.microservice.service.DepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门表 前端控制器
 * </p>
 *
 * @author liuz
 * @since 2020-07-18
 */
@RestController
@Api(tags = "部门表 相关接口")
@RequestMapping("/auth/department")
public class DepartmentController{

    @Autowired
    private DepartmentService departmentService;


    @ApiOperation(value = "新增数据", notes = "新增一条部门表数据")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "部门名称", value = "departmentName"),
        @ApiImplicitParam(name = "父部门ID", value = "parentId"),
        @ApiImplicitParam(name = "排序", value = "orderNum"),
    })
    @PostMapping("/add")
    public ResponseResult add(@Validated @RequestBody DepartmentVO vo) {
        DepartmentDTO to = vo2Dto(vo);
        departmentService.insert(to);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "删除数据", notes = "删除指定ID部门表数据")
    @ApiImplicitParam(name = "id", value = "ID")
    @DeleteMapping("/delete")
    public ResponseResult delete(@RequestParam Long id) {
        departmentService.delete(id);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "更新数据", notes = "更新指定ID部门表数据")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "ID"),
        @ApiImplicitParam(name = "部门名称", value = "departmentName"),
        @ApiImplicitParam(name = "父部门ID", value = "parentId"),
        @ApiImplicitParam(name = "排序", value = "orderNum"),
    })
    @PutMapping("/update")
    public ResponseResult update(@Validated @RequestBody DepartmentVO depar) {
        DepartmentDTO to = vo2Dto(depar);
        departmentService.updateDepartment(to);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "启用/停用", notes = "角色状态的启用/停用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID"),
            @ApiImplicitParam(name = "status", value = "状态")
    })

    @PutMapping("/enableStatus")
    @WebLog(description = "更新部门状态的启用/停用")
    public ResponseResult enableStatus(@RequestParam Long id, Integer status) {
        departmentService.enableStatus(id,status);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "查询数据", notes = "获取指定ID部门表数据")
    @ApiImplicitParam(name = "id", value = "ID")
    @GetMapping("/detail")
    public ResponseResult<DepartmentVO> detail(@RequestParam Long id) {
        DepartmentDTO dep = departmentService.selectById(id);
        return ResultGenerator.genSuccessResult(dto2Vo(dep));
    }


    @ApiOperation(value = "查询分页", notes = "获取部门表分页列表数据")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "page", value = "当前页码"),
        @ApiImplicitParam(name = "size", value = "分页大小"),
    })
    @GetMapping("/list")
    public BasePageResponse list(
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "0") Integer size,
            DepartmentVO vo) {

        LambdaQueryWrapper<Department> wrapper = Wrappers.lambdaQuery();
        wrapper.like(StringUtils.isNotEmpty(vo.getDepartmentName()),Department::getDepartmentName,vo.getDepartmentName());
        wrapper.eq(vo.getId()!=null,Department::getId,vo.getId());
        wrapper.eq(vo.getStatus()!=null,Department::getStatus,vo.getStatus());
        wrapper.ge(StringUtils.isNotEmpty(vo.getStartTimeAdd()),Department::getCreateTime,vo.getStartTimeAdd());
        wrapper.le(StringUtils.isNotEmpty(vo.getEndTimeAdd()),Department::getCreateTime,vo.getEndTimeAdd());
        wrapper.ge(StringUtils.isNotEmpty(vo.getStartTimeUp()),Department::getUpdateTime,vo.getStartTimeUp());
        wrapper.le(StringUtils.isNotEmpty(vo.getEndTimeUp()),Department::getUpdateTime,vo.getEndTimeUp());
        wrapper.eq(Department::getParentId,1);
        wrapper.eq(Department::getIsDel,0);
        wrapper.orderByDesc(Department::getOrderNum,Department::getUpdateTime);
        IPage<Department> pageInfo = departmentService.page(
                new Page<>(page, size),wrapper);
        return ResultGenerator.genSuccessResultPage(pos2Vos(pageInfo.getRecords()),pageInfo.getTotal());
    }

    @ApiOperation(value = "子部门展示", notes = "展示部门下的子菜单")
    @ApiImplicitParam(name = "id", value = "ID")
    @GetMapping("/sonDepartment")
    public ResponseResult<List<DepartmentVO>> sonDepartment(@RequestParam Long id) {
        List<DepartmentVO> department = departmentService.selectSonDepartmentId(id);
        return ResultGenerator.genSuccessResult(department);
    }


    /**
     * 对象转换 dto->vo
     * @param po
     * @return
     */
    private DepartmentVO dto2Vo(DepartmentDTO po){
        DepartmentVO r = null;
        try {
            r = po.clone(DepartmentVO.class);
        }catch (Exception e){
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return r;
    }


    /**
     * 对象转换 vo->dto
     * @param vo
     * @return
     */
    private DepartmentDTO vo2Dto(DepartmentVO vo){
        DepartmentDTO r = null;
        try {
            r = vo.clone(DepartmentDTO.class);
        }catch (Exception e){
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return r;
    }

    /**
     * 列表对象转换 po->vo
     * @param po
     * @return
     */
    private List<DepartmentVO> pos2Vos(List<Department> po){
        List<DepartmentVO> pos = po.stream().map(p-> {
            DepartmentVO vo = null;
            try {
                vo = p.clone(DepartmentVO.class);
            } catch (Exception e) {
                ExceptionEnum.FAIL_CHANGE.newException();
            }
            return vo;
        }).collect(Collectors.toList());
        return pos;
    }

}
